<template>
  <div class="myContainer">
    <el-row class="myBorderBottom">
      <el-col :span="3" class="myTitleText myLineHeight_40px">{{title}}</el-col>
      <el-col :span="2" class="myLineHeight_40px">待指派 <span>{{overdue_count}}</span> 单</el-col>
      <el-col :span="2" class="myLineHeight_40px">逾期 <span>{{undispatch_count}}</span> 单</el-col>
      <el-col :span="17" class="myTextAlignRight">
        <!-- <el-button type="primary" class="myBgGreen" @click="onAdd">新 增</el-button>
        <el-button type="primary" class="myBgGreen" @click="onMonthlyStatistics">抢单月统计</el-button> -->
        <a id="downlink"></a>
        <el-button type="primary" class="myBgGreen" @click="onExport" :loading="loadingExport">导出Excel</el-button>
      </el-col>
    </el-row>
    <!-- 搜索部分 start -->
    <el-row :gutter="10" class="myPaddingTop_10px">
      <el-col :span="6">
        <template>
          <el-cascader
            placeholder="全部项目/小区"
            :options="regionOptions"
            v-model="regionOptSelected"
            ></el-cascader>
          </el-select>
        </template>
      </el-col>
      <el-col :span="3">
        <template>
          <el-select v-model="statusValue" clearable placeholder="事务状态">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </template>
      </el-col>
      <el-col :span="6">
        <el-date-picker
          v-model="time"
          type="daterange"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-col>
      <el-col :span="3">
        <el-input placeholder="输入工单号进行查询" v-model="searchKW"></el-input>
      </el-col>
      <el-col :span="3">
        <el-button type="primary" class="myBgGreen" @click="onSearch">查询</el-button>
      </el-col>
    </el-row>
    <!-- 搜索部分 end -->
    <el-row class="mymarginTop_10px">
      <el-col :span="24">
        <template>
          <el-table
            border
            stripe
            :data="tableData"
            v-loading="loading"
            style="width: 100%">
            <el-table-column
              label="序号"
              type="index"
              width="100">
            </el-table-column>
            <el-table-column
              label="工单号"
              width="150"
              prop="id">
            </el-table-column>
            <el-table-column
              label="报修类型"
              width="100"
              prop="subject_name">
            </el-table-column>
            <el-table-column
              label="报修类别"
              prop="type_name">
            </el-table-column>
            <el-table-column
              label="上报时间"
              width="160"
              prop="commit_time">
            </el-table-column>
            <el-table-column
              width="100"
              label="事件来源">
              <template scope="scope">
                <span>{{scope.row.commit_type | sourceOfEventsText}}</span>
              </template>
            </el-table-column>
            <el-table-column
              width="100"
              label="当前状态">
              <template scope="scope">
                <span>{{scope.row.affair_status | affairStatusText}}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="报修人"
              prop="commituser_name">
            </el-table-column>
            <el-table-column
              label="联系地址"
              prop="address">
            </el-table-column>
            <el-table-column
              label="责任人"
              prop="chargeuser_name">
            </el-table-column>
            <el-table-column
              label="处理人"
              prop="dealuser_name">
            </el-table-column>
            <el-table-column
              label="所属小区"
              prop="area_name">
            </el-table-column>
            <el-table-column
              label="功能操作"
              width="100">
              <template scope="scope">
                <el-button class="look" type="text" size="small" @click="onDetailed(1,scope.row.id)">查看</el-button> 
                <span v-if="(scope.row.affair_status==1 || scope.row.affair_status==2) && isShow(243)">|</span>
                <el-button class="look" type="text" size="small" @click="onAssign(scope.row.id)" v-if="(scope.row.affair_status==1 || scope.row.affair_status==2) && isShow(243)">指派</el-button>
                <!-- <el-button class="look" type="text" size="small" @click="onAssign(scope.row.id)" v-if="scope.row.dealuser_id==null && isShow(243)">指派</el-button> -->
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-col>
    </el-row>
    <!-- 分页控件 start -->
    <div class="block">                    
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page_num"
        :page-sizes="[10, 15]"
        :page-size="page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <!-- 分页控件 end -->


    <!--指派人员弹出框 start-->
    <el-dialog title="指派处理人员" class="myRoleDialog" :visible.sync="newRoleDialogVisible" >
      <div>
        <el-input placeholder="输入关键字进行搜索" v-model="kw" class="input-with-select">
          <el-button type="primary" slot="append" class="el-icon-search" @click="onSearchR"></el-button>
        </el-input>
      </div>
      <div class="mymarginTop_10px">
        <el-tree
          class="myOV_y_400px" 
          ref="dutyDlg"
          v-loading="dutyDlgListLoading"
          :data="dutyDlgList"
          :props="dutyDlgProps"
          node-key="staff_id"
          @check-change="onChange"
          :render-content="renderContent"
          :filter-node-method="filterNode"
          show-checkbox>
        </el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" class="myBgGreen" @click="newRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" class="myBgGreen" @click="onAssignSub">提 交</el-button>
      </div>
    </el-dialog>
    <!--指派人员弹出框 end-->
  </div>
</template>  

<style scoped>
  .myContainer{
    background: #fff;
    padding: 10px;
  }
  .myHeadeTitle{
    color: #000;
    font-weight: 500;
    font-size: 16px;
    padding-bottom: 10px;
    border-bottom: 1px solid #dbdbdb;
    margin-bottom:10px; 
  }
  .myHeadeTitle:before,.myHeadeTitle:after{
    content: " ";
    display: block;
    clear: both;
  }
  .myBgGreen{
    background: #00c2a9;
    border-color: #00c2a9;
    color: #fff;
    margin-top: 2px;
  }
  .myLineHeight_35px{
    line-height: 35px;
  }
  .myTextAlignRight{
    text-align: right;
  }
  .myBgGreen:hover{
    background: #33ceba;
  }
  .myPaddingTop_10px{
    padding-top: 10px;
  }  
  .myLeftMsg{
    line-height: 40px;
    text-align: right;
    padding-right: 10px;
  }
  .myPaddingBottom_10px{
    padding-bottom: 10px;
  }
  .myVA_M{
    vertical-align: middle;
  }
  .myPadding_20px{
    padding: 20px;
  }    
  .myTitleText{
    font-weight: 500;
    font-size: 16px;
  }
  .myLineHeight_40px{
    line-height: 40px;
  }
  .myBorderBottom{
    border-bottom:1px solid #dbdbdb;
    padding-bottom: 5px;
  }
  .mymarginTop_10px{
    padding-top: 10px;
  }
  .myOV_y_400px{
    max-height: 400px;
    min-height: 200px;
    overflow-y:scroll;
    border:1px solid #f2f2f2;
  }
</style>

<script>
  import { getRepairList , sourceOfEvents , affairStatus , setDealuser , getRepairCount , keyMapping } from '@/api/affair_setting';
  import { getRegion } from '@/utils/localstorage';
  import { getStaffList } from '@/api/staff';
  import { extractAreaIds , onSetArea } from '@/utils/misc';
  let XLSX = require('xlsx');
  export default {
     data(){
      return{
        title:"报修管理",
        loading:false,
        housValue:"",
        housOptions:[],
        value1:"",
        tableData:[],
        page_num:null,
        page_size:null,
        total:null,
        regionOptions: [],
        regionOptSelected: [],
        dutyDlgListLoading:false,
        dutyDlgList:[],
        dutyDlgProps: {
          children: 'children',
          label: 'user_name'
        },
        newRoleDialogVisible:false,
        searchKW:"",
        id:"",
        startTime:"",
        endTime:"",
        overdue_count:"",//逾期数量
        undispatch_count:"",//待指派数量
        kw:"",
        time:[],
        loadingExport:false,
        statusValue:'',
        statusOptions:[
          {value:"0",label:"立项"},
          {value:"1",label:"未分配"},
          {value:"2",label:"分配未处理"},
          {value:"3",label:"处理完毕，未评价"},
          {value:"4",label:"评价未回访"},
          {value:"5",label:"回访，结束"},
          {value:"7",label:"重新处理"}
        ]
      }
    },
    components: {
      
    },
    watch: {
      kw(val) {
        this.$refs.dutyDlg.filter(val);
      }
    },
    filters: {
      sourceOfEventsText: function(value) {
        return sourceOfEvents[value];
      },
      affairStatusText: function(val){
        return affairStatus[val];
      }
    },
    computed: {
      areaIds() {
        return extractAreaIds(this.regionOptSelected, this.regionOptions);
      }
    },
    mounted(){
      document.title = this.title;
      this.regionOptions = getRegion();
      this.regionOptSelected.push(this.regionOptions[0].value,this.regionOptions[0].children[0].value,this.regionOptions[0].children[0].children[0].value);
      
      this.onGetRepairList();
      this.onGetRepairCount();
      this.outFile = document.getElementById('downlink');
    },
    methods:{
      filterNode(value, data) {
        if (!value) return true;
        return data.user_name.indexOf(value) !== -1;
      },
      onGetRepairList(){//获取报修列表
        let vm=this;
        vm.loading=true;
        if(vm.time){
          vm.startTime=this.time[0];
          vm.endTime=this.time[1];
        }else{
          vm.startTime="";
          vm.endTime="";
        }
        let areaid=vm.areaIds;//小区id------------------------
        // console.log("搜索的小区id",areaid,"开始时间",vm.startTime,"结束时间",vm.endTime);
        let params={
          start_time:vm.startTime,//开始时间
          end_time:vm.endTime,//结束时间
          keyword:vm.searchKW,//搜索关键词
          page_num:vm.page_num,
          page_size:vm.page_size,
          status:vm.statusValue
        }
        getRepairList(areaid,params).then(response =>{
          let res=response.data;
          vm.page_size=res.page_size;
          vm.page_num=res.page_num;
          vm.total=res.total;
          vm.tableData=res.rows;
          vm.loading=false;
          // console.log("拉取报修列表成功",res);
        }).catch(error =>{
          vm.loading=false;
          //console.log("拉取报修列表失败",error);
        })
      },
      onDetailed:function(val,id){
        let vm=this;
        if(val==1){//工区/家庭
          vm.$router.push({
            path:'/yhbxxx',
            query: {
              id:id,
              time:vm.time, 
              keyword:vm.searchKW, 
              page_num:vm.page_num,
              status:vm.statusValue,
              areaid:vm.areaIds
            }
          })
        }else if(val==2){//告警处理
          this.$router.push({
            path:'/yhbxcl',
            query: {}
          })
        }
        
      },
      onGetRepairCount(){//获取小区报修项目统计数据
        let vm=this;
        let areaid=vm.areaIds;//小区id---------------------------------------
        getRepairCount(areaid).then(response => {
          let res=response.data;
          vm.overdue_count=res.overdue_count;//逾期数量
          vm.undispatch_count=res.undispatch_count;//待指派数量
          // console.log("拉取小区报修统计成功",res);
        }).catch(error => {
          //console.log("拉取小区报修统计失败",error);
        })
      },
      handleSizeChange(val) {//每页条数控制
        this.page_size = val;
        this.onGetRepairList();
      },
      handleCurrentChange(val) {//每页
        let backData=window.localStorage.getItem("backData");
        if(backData){
          let { time, keyword, page_num, status , areaid }=JSON.parse(backData);
          this.time=time;
          this.searchKW=keyword;
          this.statusValue=status;
          this.page_num = Number(page_num);
          this.regionOptSelected=onSetArea(this.regionOptions,areaid);
          window.localStorage.removeItem("backData");
        }else{
          this.page_num = val;
        }
        this.onGetRepairList();
      },
      onAdd:function(){
        this.$router.push({
          path:'/yhbxAdd',
          query: {type: 'add'}
        })
      },
      onMonthlyStatistics:function(){//跳转到抢单月统计页面
        this.$router.push({
          path:'/yhbxytt',
          query: {}
        })
      },
      onAssign(id){//指派执行人
        this.id=id;
        this.fetchStaff();
        this.newRoleDialogVisible = true;
      },
      fetchStaff() {//获取人员列表
        let vm = this;
        this.dutyDlgListLoading = true;
        vm.kw="";
        let params = {
          kw:vm.kw,
          is_fuzzy:true,
          page_num: 1,
          page_size: 10000,
          ril: 'S',
          area_id:vm.areaIds
        };
        getStaffList(params)
        .then(response => {
          vm.dutyDlgList = response.data.rows;
          // console.log(vm.dutyDlgList)
          vm.dutyDlgListLoading = false;
        })
        .catch(error => {
          vm.dutyDlgListLoading = false;
        })
      },
      onChange(a,b,c){
        let vm=this;
        if(b){
          vm.$refs.dutyDlg.setCheckedKeys([]);
          vm.$refs.dutyDlg.setCheckedKeys([a.staff_id]);
        }else{
          vm.$refs.dutyDlg.setCheckedKeys([]);
        }
      },
      renderContent:function(createElement, { node, data, store }) {
        var vm = this;
        return createElement(
          'div', 
          {
            attrs:{
              style:"width:100%",
              title:`联系方式：${node.data.phone}`
            }
          },
          [
            createElement('span', node.label),
            createElement('span', 
              {attrs:{
                style:"float: right; margin-right: 20px"
              }},
              `${node.data.dept_name}`
            )
          ]
        );
      },
      onAssignSub(){
        let vm=this;
        var duty = vm.$refs.dutyDlg.getCheckedNodes();
        if (duty.length > 0) {
          vm.dutyName = duty[0].user_name;
          vm.dutyId = duty[0].staff_id;
        }       
        const params={
          affair_id:vm.id,//事务id（工单id）
          dealuser_id:vm.dutyId//处理用户id
        }
        // console.log(params)
        setDealuser(params).then(response =>{
          let res=response.data;
          vm.$message.success("执行成功！");
          vm.onGetRepairList();
        }).catch(error =>{
          vm.$message.error("执行失败！"+error.response.data.error_msg);
          // console.log("指派处理人失败",error);
        })
        vm.newRoleDialogVisible = false;
      },
      onSearch(){
        this.onGetRepairList();
        this.onGetRepairCount();
      },
      onSearchR(){
        this.fetchStaff();
      },
      onExport(){
        let vm=this;
        let areaid=vm.areaIds;//小区id------------------------
        let params={
          start_time:vm.time[0]||'',//开始时间
          end_time:vm.time[1]||'',//结束时间
          keyword:vm.searchKW,//搜索关键词
          page_num:vm.page_num,
          page_size:vm.total
        }
        vm.loadingExport=true;
        getRepairList(areaid,params).then(response =>{
          let res=response.data.rows;
          if(res.length==0){
            vm.loadingExport=false;
            vm.$message.info("没有可导出的数据！");
            return;
          }
          let data = [{}],name="用户报修数据";
          for (let k in res[0]) {
            data[0][k] = k
          }
          data = data.concat(res);
          vm.downloadExl(data, name);
          vm.loadingExport=false;
          vm.$message.success(`导出成功！总共${res.length}条数据。`);
        }).catch(error =>{
          vm.loadingExport=false;
          vm.$message.error("导出失败！");
          //console.log(error);
        })
      },
      downloadExl: function (json, downName, type) {  // 导出到excel
        let keyMap = []
        for (let k in json[0]) {
          keyMap.push(k);
        }
        let tmpdata = [] 
        json.map((v, i) => keyMap.map((k, j) => Object.assign({}, {
          v: v[k],
          position: (j > 25 ? this.getCharCol(j) : String.fromCharCode(65 + j)) + (i + 1)
        }))).reduce((prev, next) => prev.concat(next)).forEach(function (v) {
          tmpdata[v.position] = {
            v: keyMapping[v.v] || v.v
          }
        })
        let outputPos = Object.keys(tmpdata)  
        let tmpWB = {
          SheetNames: ['用户报修数据'], 
          Sheets: {
            '用户报修数据': Object.assign({},
              tmpdata, 
              {
                '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] 
              })
          }
        }
        let tmpDown = new Blob([this.s2ab(XLSX.write(tmpWB,
          {bookType: (type === undefined ? 'xlsx' : type), bookSST: false, type: 'binary'} 
        ))], {
          type: ''
        }) 
        var href = URL.createObjectURL(tmpDown)  
        this.outFile.download = downName + '.xlsx'  
        this.outFile.href = href  
        this.outFile.click()  

        setTimeout(function () {  
          URL.revokeObjectURL(tmpDown) 
        }, 100)
      },
      s2ab: function (s) { 
        var buf = new ArrayBuffer(s.length)
        var view = new Uint8Array(buf)
        for (var i = 0; i !== s.length; ++i) {
          view[i] = s.charCodeAt(i) & 0xFF
        }
        return buf
      },
      getCharCol: function (n) { 
        let s = ''
        let m = 0
        while (n > 0) {
          m = n % 26 + 1
          s = String.fromCharCode(m + 64) + s
          n = (n - m) / 26
        }
        return s
      }
    }
    

  }

</script>  



